package com.yyaccp.hncc.sms.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.yyaccp.hncc.sms.domain.SmsSkdRuleItem;
import com.yyaccp.hncc.sms.service.ISmsSkdRuleItemService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.yyaccp.hncc.sms.domain.SmsSkd;
import com.yyaccp.hncc.sms.service.ISmsSkdService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.*;
//com.yyaccp.hncc.common模块的包引入
import com.yyaccp.hncc.common.vo.sms.SmsSkdVO;
import com.yyaccp.hncc.common.util.BeanCopierUtil;

import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 排班时间Controller
 *
 * @author ruoyi
 * @date 2020-08-23
 */
@Api(tags = "排班时间")
@RestController
@RequestMapping("/sms/skd")
public class SmsSkdController extends BaseController {
    @Autowired
    private ISmsSkdService smsSkdService;

    @Autowired
    private ISmsSkdRuleItemService smsSkdRuleItemService;

/**
 * 查询排班时间列表
 *
 */
@PreAuthorize("@ss.hasPermi('sms:skd:list')")
@GetMapping("/list")
@ApiOperation(value = "查询排班时间" , notes = "查询所有排班时间" ,
        code = 200, produces = "application/json" , protocols = "Http" ,
        response = TableDataInfo.class, httpMethod = "GET")
@ApiResponses({
        @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
        @ApiResponse(code = 303, message = "重定向"),
        @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
        @ApiResponse(code = 500, message = "系统内部错误"),
        @ApiResponse(code = 404, message = "资源，服务未找到"),
        @ApiResponse(code = 200, message = "操作成功"),
        @ApiResponse(code = 401, message = "未授权"),
        @ApiResponse(code = 403, message = "访问受限，授权过期")
})
@ApiParam(name = "SmsSkdVO对象" , type = "SmsSkdVO")
        public TableDataInfo list(SmsSkdVO smsSkdVO) {
        //将Vo转化为实体
        SmsSkd smsSkd=BeanCopierUtil.copy(smsSkdVO,SmsSkd. class);
        startPage();
        List<SmsSkd> list = smsSkdService.selectSmsSkdList(smsSkd);
        TableDataInfo tableDataInfo = getDataTable(list);
        //替换集合
        tableDataInfo.setRows(BeanCopierUtil.copy(tableDataInfo.getRows(), SmsSkdVO.class));
        return tableDataInfo;
    }
    
    /**
     * 导出排班时间列表
     */
    @PreAuthorize("@ss.hasPermi('sms:skd:export')")
    @Log(title = "排班时间" , businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation(value = "导出排班时间表" , notes = "导出所有排班时间" ,
            code = 200, produces = "application/json" , protocols = "Http" ,
            response = TableDataInfo.class, httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "SmsSkdVO对象" , type = "SmsSkdVO")
    public AjaxResult export(SmsSkdVO smsSkdVO) {
        //将VO转化为实体
        SmsSkd smsSkd=BeanCopierUtil.copy(smsSkdVO,SmsSkd. class);
        List<SmsSkdVO> list = BeanCopierUtil.copy(smsSkdService.selectSmsSkdList(smsSkd),SmsSkdVO.class);
        ExcelUtil<SmsSkdVO> util = new ExcelUtil<SmsSkdVO>(SmsSkdVO.class);
        return util.exportExcel(list, "skd");
    }

    /**
     * 获取排班时间详细信息
     */
    @PreAuthorize("@ss.hasPermi('sms:skd:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取排班时间详细信息" ,
            notes = "根据排班时间id获取科室信息" , code = 200,
            produces = "application/json" , protocols = "Http" , response = AjaxResult.class,
            httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "smsSkd.id" , type = "Long")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(BeanCopierUtil.copy(smsSkdService.selectSmsSkdById(id),SmsSkdVO.class));
    }

    /**
     * 新增排班时间
     */
    @PreAuthorize("@ss.hasPermi('sms:skd:add')")
    @Log(title = "新增排班时间" , businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增排班时间信息" , notes = "新增排班时间信息" , code = 200,
            produces = "application/json" , protocols = "Http" , response = AjaxResult.class,
            httpMethod = "POST")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "SmsSkdVO对象" , type = "SmsSkdVO")
    public AjaxResult add(@RequestBody SmsSkdVO smsSkdVO) throws ParseException{
        generateSmsSkd(smsSkdVO.getSmsSkdRuleId(),smsSkdVO.getDeptId(),smsSkdVO.getCreateDate(),smsSkdVO.getEndDate());
        return toAjax(1);
    }

    /**
     * 排班计划生成
     * @param smsSkdRuleId
     * @param deptId
     * @param createDate
     * @param endDate
     * @throws ParseException
     */
    public void generateSmsSkd(Long smsSkdRuleId,Long deptId,String createDate, String endDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date begin = sdf.parse(createDate);
        Date end = sdf.parse(endDate);
        //日期集合
        List<Date> lDate = findDates(begin, end);

        //排班时间对象
        SmsSkd smsSkd;

        //根据排班规则查询条目集合
        List<SmsSkdRuleItem> smsSkdRuleItems = smsSkdRuleItemService.selectSmsSkdRuleItemById(smsSkdRuleId);

        //生成排班时间之前删除当前规则的所有排班
        smsSkdService.deleteSmsSkdById(smsSkdRuleId);

        for (int i = 0; i < smsSkdRuleItems.size(); i++) {
            for (int j = 0; j < lDate.size(); j++) {
                smsSkd = new SmsSkd();
                //上班日期
                smsSkd.setDate(lDate.get(j));
                //状态
                smsSkd.setStatus(1);
                //剩余号数
                smsSkd.setRemain(smsSkdRuleItems.get(i).getSkLimit());
                //员工id
                smsSkd.setStaffId(smsSkdRuleItems.get(i).getStaffId());
                //科室id
                smsSkd.setDeptId(deptId);
                //挂号限额
                smsSkd.setSkLimit(smsSkdRuleItems.get(i).getSkLimit());
                //排班规则id
                smsSkd.setSmsSkdRuleId(smsSkdRuleId);
                //天数数组
                String[] day = new String[2];
                switch (dateToWeek(sdf.format(lDate.get(j)))){
                    case "星期一":
                        day[0] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(0,1);
                        day[1] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(1,2);
                        break;
                    case "星期二":
                        day[0] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(2,3);
                        day[1] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(3,4);
                        break;
                    case "星期三":
                        day[0] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(4,5);
                        day[1] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(5,6);
                        break;
                    case "星期四":
                        day[0] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(6,7);
                        day[1] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(7,8);
                        break;
                    case "星期五":
                        day[0] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(8,9);
                        day[1] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(9,10);
                        break;
                    case "星期六":
                        day[0] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(10,11);
                        day[1] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(11,12);
                        break;
                    case "星期日":
                        day[0] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(12,13);
                        day[1] = smsSkdRuleItems.get(i).getDaysOfWeek().substring(13,14);
                        break;
                    default:
                        break;
                }
                //上午等于1 插入一条数据
                if(day[0].equals("1")){smsSkd.setNoon(0);smsSkdService.insertSmsSkd(smsSkd);}
                //下午等于1 插入一条数据
                if(day[1].equals("1")){smsSkd.setNoon(1);smsSkdService.insertSmsSkd(smsSkd);}
            }
        }
    }

    /**
     * 返回日期集合
     * @param dBegin
     * @param dEnd
     * @return
     */
    public static List<Date> findDates(Date dBegin, Date dEnd)
    {
        List lDate = new ArrayList();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime()))
        {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }

    /**
     * 根据日期判断星期
     * @param datetime
     * @return
     */
    public String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        // 获得一个日历
        Calendar cal = Calendar.getInstance();
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 指示一个星期中的某天
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }



    /**
     * 修改排班时间
     */
    @PreAuthorize("@ss.hasPermi('sms:skd:edit')")
    @Log(title = "排班时间" , businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改排班时间信息" , notes = "修改排班时间信息" , code = 200,
            produces = "application/json" , protocols = "Http" , response = AjaxResult.class,
            httpMethod = "PUT")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "SmsSkdVO对象" , type = "SmsSkdVO")
    public AjaxResult edit(@RequestBody SmsSkdVO smsSkdVO) {
        return toAjax(smsSkdService.updateSmsSkd(BeanCopierUtil.copy(smsSkdVO,SmsSkd. class)));
    }

    /**
     * 删除排班时间
     */
    @PreAuthorize("@ss.hasPermi('sms:skd:remove')")
    @Log(title = "排班时间" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除排班时间信息" , notes = "删除排班时间信息" , code = 200,
            produces = "application/json" , protocols = "Http" , response = AjaxResult.class,
            httpMethod = "DELETE")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "smsSkd.id" , type = "Long[]")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(smsSkdService.deleteSmsSkdByIds(ids));
    }
}
